package walls.interceptor;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import walls.exception.AuthException;
import walls.utils.JwtTokenUtil;


@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    JwtTokenUtil jwtTokenUtil;
    private static final String AUTH_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        // 排除登录等不需要验证的路径
        if (request.getRequestURI().contains("/login") ||
                request.getRequestURI().contains("/public")) {
            return true;
        }

        String authHeader = request.getHeader(AUTH_HEADER);

        if (authHeader == null || !authHeader.startsWith(TOKEN_PREFIX)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new AuthException("缺少有效的授权令牌");
//            response.getWriter().write("缺少有效的授权令牌");
//            return false;
        }

        String token = authHeader.substring(TOKEN_PREFIX.length());

        if (!jwtTokenUtil.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            response.getWriter().write("无效或过期的令牌");
            throw new AuthException("无效或过期的令牌");

        }

        // 将用户信息添加到请求属性中，供控制器使用
//        request.setAttribute("userId", jwtTokenUtil.getUserIdFromToken(token));
//        request.setAttribute("username", jwtTokenUtil.getUsernameFromToken(token));
//        request.setAttribute("roles", jwtTokenUtil.getRolesFromToken(token));

        return true;
    }
}